//package com.hanlink.dsp.ui.fragment;
//
//import android.annotation.SuppressLint;
//import android.content.Context;
//import android.content.Intent;
//import android.net.Uri;
//import android.os.Bundle;
//import android.text.InputType;
//import android.text.TextUtils;
//import android.view.Gravity;
//import android.view.LayoutInflater;
//import android.view.View;
//import android.view.ViewGroup;
//import android.view.animation.BounceInterpolator;
//import android.widget.BaseAdapter;
//import android.widget.EditText;
//import android.widget.ImageButton;
//import android.widget.ImageView;
//import android.widget.TextView;
//import android.widget.Toast;
//
//import androidx.annotation.NonNull;
//import androidx.core.content.FileProvider;
//
//import com.blankj.utilcode.util.SPUtils;
//import com.hanlink.dsp.BtDspApplication;
//import com.hanlink.dsp.DspContext;
//import com.hanlink.dsp.DspSettings;
//import com.hanlink.dsp.R;
//import com.hanlink.dsp.ca.model.channel.EqChannel;
//import com.hanlink.dsp.ca.model.channel.LevelChannel;
//import com.hanlink.dsp.ca.model.channel.SummingChannel;
//import com.hanlink.dsp.ca.model.channel.XoverChannel;
//import com.hanlink.dsp.model.LocalStorage;
//import com.hanlink.dsp.model.UserProfile;
//import com.hanlink.dsp.ui.CaDspActivity;
//import com.hanlink.dsp.util.DataUtil;
//import com.hanlink.dsp.util.DialogHelper;
//import com.hanlink.dsp.util.ToolUtil;
//import com.qztech.sdk.ui.fragment.BaseDrawerFragment;
//import com.qztech.sdk.ui.widget.SwipeMenuListView;
//
//import org.xutils.DbManager;
//import org.xutils.ex.DbException;
//import org.xutils.x;
//
//import java.io.File;
//import java.io.IOException;
//import java.text.SimpleDateFormat;
//import java.util.List;
//
//import io.reactivex.Observable;
//import io.reactivex.ObservableOnSubscribe;
//import io.reactivex.android.schedulers.AndroidSchedulers;
//import io.reactivex.schedulers.Schedulers;
//
//public class SaveDrawerFragment extends BaseDrawerFragment {
//
//    private final static String PASSOWRD = "666666";
//    private List<UserProfile> dspSettingsList;
//    private SettingAdapter mSettingAdapter;
//    private DbManager db;
//
//    @Override
//    public void onViewCreated(@NonNull final View view, Bundle savedInstanceState) {
//        super.onViewCreated(view, savedInstanceState);
//        TextView mTxtSaveBase = view.findViewById(R.id.txtSaveBase);
//        TextView mTxtSaveAdvanced = view.findViewById(R.id.txtSaveAdvanced);
//        SwipeMenuListView mDrawerListView = view.findViewById(R.id.lvItems);
//        mDrawerListView.setOnItemClickListener((parent, view1, position, id) -> {
//            final UserProfile userProfile = dspSettingsList.get(position);
//            if (userProfile.getMode() == 1) {
//                String oldPassword = SPUtils.getInstance().getString(DspContext.KEY_PWD, DspContext.PASSOWRD);
//                if (TextUtils.isEmpty(oldPassword)) {
//                    showChangePasswordDialog(getActivity());
//                    return;
//                }
//                showEnterPasswordDialog(getActivity(), v1 -> onItemSelected(view1, position, userProfile));
//            } else {
//                onItemSelected(view1, position, userProfile);
//            }
//
//        });
//        mSettingAdapter = new SettingAdapter();
//        db = x.getDb(BtDspApplication.daoConfig);
//        mDrawerListView.setAdapter(mSettingAdapter);
//
//        // set creator
//        mDrawerListView.setMenuCreator(ToolUtil.buildDeleteCreator(getActivity()));
//
//        // step 2. listener item click event
//        mDrawerListView.setOnMenuItemClickListener((position, menu, index) -> {
//            if (index == 0) {// delete
//                final UserProfile userProfile = dspSettingsList.get(position);
//                if (userProfile.getMode() == 1) {
//                    showEnterPasswordDialog(getActivity(), v1 -> delete(position));
//                } else {
//                    delete(position);
//                }
//            }
//        });
//
//
//        // set SwipeListener
//        mDrawerListView.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {
//
//            @Override
//            public void onSwipeStart(int position) {
//                // swipe start
//            }
//
//            @Override
//            public void onSwipeEnd(int position) {
//                // swipe end
//
//            }
//        });
//
//        // other setting
//        mDrawerListView.setCloseInterpolator(new BounceInterpolator());
//
//        // test item long click
//        mDrawerListView.setOnItemLongClickListener((parent, view12, position, id) -> false);
//
//        mTxtSaveAdvanced.setOnClickListener(v -> {
//            SPUtils spUtils = SPUtils.getInstance(Context.MODE_PRIVATE);
//            String oldPassword = spUtils.getString(DspContext.KEY_PWD, DspContext.PASSOWRD);
//            if (TextUtils.isEmpty(oldPassword)) {
//                showChangePasswordDialog(getActivity());
//            } else {
//                showEnterPasswordDialog(getActivity(), v1 -> showSaveNewSettingsDialog(1));
//            }
//
//        });
//        mTxtSaveBase.setOnClickListener(v -> showSaveNewSettingsDialog(0));
//
//    }
//
//    private void onItemSelected(View view, int position, UserProfile userProfile) {
//        DspSettings.USER_PROFILE = userProfile;
//        sp.edit().putInt(STATE_SELECTED_POSITION, position).apply();
//        if (mCallbacks != null) {
//            mCallbacks.onDrawerItemSelected(Gravity.START, view, position, dspSettingsList.get(position).getId());
//        }
//    }
//
//    private void showEnterPasswordDialog(Context ctx, View.OnClickListener listener) {
//        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(ctx);
//        View view = LayoutInflater.from(ctx).inflate(R.layout.dialig_view_show_password, null, false);
//        TextView tvCancel = view.findViewById(R.id.tvCancel);
//        TextView tvOk = view.findViewById(R.id.tvOk);
//        TextView tvChange = view.findViewById(R.id.tvChange);
//        TextView etPassword = view.findViewById(R.id.etPassword);
//        SPUtils spUtils = SPUtils.getInstance(Context.MODE_PRIVATE);
//        String oldPassword = spUtils.getString(DspContext.KEY_PWD, DspContext.PASSOWRD);
//        androidx.appcompat.app.AlertDialog alertDialog = builder.setView(view)
//                .setTitle(R.string.title_input_password)
//                .setCancelable(false)
//                .create();
//        tvCancel.setOnClickListener(v -> {
//            alertDialog.dismiss();
//        });
//        tvOk.setOnClickListener(v -> {
//            if (etPassword.getText() == null || etPassword.getText().length() == 0) {
//                Toast.makeText(ctx, "Please enter password!", Toast.LENGTH_SHORT).show();
//                return;
//            }
//
//            if (oldPassword.equals(etPassword.getText().toString())) {
//                if (listener != null) {
//                    listener.onClick(v);
//                }
//                alertDialog.dismiss();
//            }
//        });
//        tvChange.setOnClickListener(v -> {
//            alertDialog.dismiss();
//            showChangePasswordDialog(getActivity());
//        });
//        tvCancel.setOnClickListener(v -> alertDialog.dismiss());
//        alertDialog.show();
//    }
//
//    private void showChangePasswordDialog(Context ctx) {
//        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(ctx);
//        View view = LayoutInflater.from(ctx).inflate(R.layout.dialig_view_change_password, null, false);
//        EditText etOldPassword = view.findViewById(R.id.etOldPassword);
//        TextView tvOldPasswordLabel = view.findViewById(R.id.tvOldPasswordLabel);
//        EditText etNewPassword = view.findViewById(R.id.etNewPassword);
//        EditText etNewPasswordAgain = view.findViewById(R.id.etNewPasswordAgain);
//        TextView tvCancel = view.findViewById(R.id.tvCancel);
//        TextView tvOk = view.findViewById(R.id.tvOk);
//        SPUtils spUtils = SPUtils.getInstance(Context.MODE_PRIVATE);
//        String oldPassword = spUtils.getString(DspContext.KEY_PWD, DspContext.PASSOWRD);
//        if (TextUtils.isEmpty(oldPassword)) {
//            etOldPassword.setVisibility(View.GONE);
//            tvOldPasswordLabel.setVisibility(View.GONE);
//        }
//        androidx.appcompat.app.AlertDialog alertDialog = builder.setView(view)
//                .setTitle(R.string.title_change_password)
//                .setCancelable(false)
//                .create();
//        tvCancel.setOnClickListener(v -> {
//            alertDialog.dismiss();
//        });
//        tvOk.setOnClickListener(v -> {
//            if (!TextUtils.isEmpty(oldPassword) && (etOldPassword.getText() == null || etOldPassword.getText().length() == 0)) {
//                Toast.makeText(ctx, "Please enter old password!", Toast.LENGTH_SHORT).show();
//                return;
//            }
//            if (!TextUtils.isEmpty(oldPassword) && !oldPassword.equals(etOldPassword.getText().toString())) {
//                Toast.makeText(ctx, R.string.save_settings_password_error, Toast.LENGTH_SHORT).show();
//                return;
//            }
//            if (etNewPassword.getText() == null || etNewPassword.getText().length() == 0) {
//                Toast.makeText(ctx, "Please enter new password!", Toast.LENGTH_SHORT).show();
//                return;
//            }
//            if (etNewPasswordAgain.getText() == null || etNewPasswordAgain.getText().length() == 0) {
//                Toast.makeText(ctx, "Please enter new password again!", Toast.LENGTH_SHORT).show();
//                return;
//            }
//            if (etNewPassword.getText().toString().equals(etNewPasswordAgain.getText().toString())) {
//                spUtils.put(DspContext.KEY_PWD, etNewPassword.getText().toString().trim());
//                Toast.makeText(ctx, "Password changed!", Toast.LENGTH_SHORT).show();
//                alertDialog.dismiss();
//            } else {
//                Toast.makeText(ctx, "Please enter same password!", Toast.LENGTH_SHORT).show();
//            }
//
//        });
//        alertDialog.show();
//    }
//
//
//    private void showSaveNewSettingsDialog(final int mode) {
//        final EditText editText = new EditText(getActivity());
//        editText.setInputType(InputType.TYPE_CLASS_TEXT);
//        DialogHelper.confirm(getActivity(), editText, R.string.title_save_add_confirm, R.string.nullvalue,
//                R.string.ok, R.string.cancel, (dialog, which) -> {
//                    saveAsNewSettings(editText.getText().toString(), mode);
//                    //mDrawerListView.setItemChecked(mSettingAdapter.getCount() - 1, true);
//                    dialog.cancel();
//                });
//    }
//
//    /**
//     * 保存配置
//     */
//    protected void saveAsNewSettings(String name, int mode) {
//        try {
//            if (TextUtils.isEmpty(name)) {
//                Toast.makeText(getActivity(), R.string.name_empty, Toast.LENGTH_SHORT).show();
//                return;
//            }
//
//            UserProfile userProfile = new UserProfile(name);
//            userProfile.setMode(mode);
//            db.saveOrUpdate(userProfile);
//            System.out.println(userProfile + ">>>>>>>>>>>>>>>>>>>>>>>>>>");
//            int userProfileId = userProfile.getId();
//            DspSettings.USER_PROFILE = userProfile;
//            if (userProfileId > 0) {
//                DspSettings.HOME_SETTINGS.setId(0);
//                DspSettings.HOME_SETTINGS.setRefId(userProfileId);
//
//                db.saveOrUpdate(DspSettings.HOME_SETTINGS);
//                System.out.println(DspSettings.HOME_SETTINGS + ">>DDDDDDDDDD>>>>>>>>>>>>>>>>>>>>>>>>" + "::userProfileId====:" + userProfileId);
//
//                DspSettings.SUMMING_SETTINGS.setId(0);
//                DspSettings.SUMMING_SETTINGS.setRefId(userProfileId);
//                db.saveOrUpdate(DspSettings.SUMMING_SETTINGS);
//                int summing_setting_id = DspSettings.SUMMING_SETTINGS.getId();
//                if (summing_setting_id > 0) {
//                    for (SummingChannel summingChannel : DspSettings.SUMMING_SETTINGS.getSummingChannels()) {
//                        summingChannel.setId(0);
//                        summingChannel.setSettingsId(summing_setting_id);
//                    }
//                    db.saveOrUpdate(DspSettings.SUMMING_SETTINGS.getSummingChannels());
//                }
//
//                //保存EQ EqChannel 数据
//                DspSettings.EQ_SETTINGS.setId(0);
//                DspSettings.EQ_SETTINGS.setRefId(userProfileId);
//                db.saveOrUpdate(DspSettings.EQ_SETTINGS);
//
//                int eqSettingsId = DspSettings.EQ_SETTINGS.getId();
//                System.out.println(":::::::::::save EQ_SETTINGS" + eqSettingsId);
//                if (eqSettingsId > 0) {
//                    for (EqChannel eqChannel : DspSettings.EQ_SETTINGS.getEqChannel()) {
//                        eqChannel.setId(0);
//                        eqChannel.setSettingsId(eqSettingsId);
//                    }
//                    db.saveOrUpdate(DspSettings.EQ_SETTINGS.getEqChannel());
//                }
//
//
//                //保存XOVER 数据
//                DspSettings.XOVER_SETTINGS.setId(0);
//                DspSettings.XOVER_SETTINGS.setRefId(userProfileId);
//                db.saveOrUpdate(DspSettings.XOVER_SETTINGS);
//
//                int xOverSettingsId = DspSettings.XOVER_SETTINGS.getId();
//                if (xOverSettingsId > 0) {
//                    for (XoverChannel channel : DspSettings.XOVER_SETTINGS.getChannel()) {
//                        channel.setId(0);
//                        channel.setSettingsId(xOverSettingsId);
//                    }
//                    db.saveOrUpdate(DspSettings.XOVER_SETTINGS.getChannel());
//                }
//
//
//                //保存ADVANCE 数据
//                DspSettings.ADVANCE_SETTINGS.setId(0);
//                DspSettings.ADVANCE_SETTINGS.setRefId(userProfileId);
//                db.saveOrUpdate(DspSettings.ADVANCE_SETTINGS);
//
//                int advanceSettingsId = DspSettings.ADVANCE_SETTINGS.getId();
//                if (advanceSettingsId > 0) {
//                    for (LevelChannel channel : DspSettings.ADVANCE_SETTINGS.getChannel()) {
//                        channel.setId(0);
//                        channel.setSettingsId(advanceSettingsId);
//                    }
//                    db.saveOrUpdate(DspSettings.ADVANCE_SETTINGS.getChannel());
//                }
//            }
//            if (mCallbacks != null) {
//                mCallbacks.onDrawerItemAdded(Gravity.LEFT, null, 0, 0);
//            }
//            reloadSettings();
//        } catch (DbException e) {
//            e.printStackTrace();
//            Toast.makeText(getActivity(), R.string.db_name_not_unique, Toast.LENGTH_SHORT).show();
//        }
//    }
//
//    public void reloadSettings() {
//        try {
//            dspSettingsList = db.selector(UserProfile.class)
//                    .orderBy("id")
//                    .limit(50).findAll();
//        } catch (DbException e) {
//            e.printStackTrace();
//        }
//        mSettingAdapter.notifyDataSetChanged();
//    }
//
//    private void delete(final int position) {
//        DialogHelper.confirm(getActivity(), R.string.title_save_delete_confirm, R.string.save_message_delete,
//                R.string.ok, R.string.cancel, (dialog, which) -> {
//                    new LocalStorage().deleteSettings(getActivity().getApplicationContext(), db, dspSettingsList.get(position).getId());
//
//                    if (mCallbacks != null) {
//                        mCallbacks.onDrawerItemDeleted(Gravity.LEFT, null, dspSettingsList.get(position).getId(), 0);
//                    }
//                    dspSettingsList.remove(position);
//                    mSettingAdapter.notifyDataSetChanged();
//                    int newPosition = position - 1;
//                    if (newPosition < 0) {
//                        newPosition = 0;
//                    }
//                    //mDrawerListView.setItemChecked(newPosition, true);
//                    dialog.cancel();
//                });
//    }
//
//    @Override
//    public void onPause() {
//        super.onPause();
//    }
//
//
//    @Override
//    public void onRefreshFragment(int cmd) {
//
//    }
//
//    @Override
//    public void onResume() {
//        super.onResume();
//        reloadSettings();
//    }
//
//    @Override
//    protected int getResourceId() {
//        return R.layout.fragment_drawer_save;
//    }
//
//    class SettingAdapter extends BaseAdapter {
//        private final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
//        private final SimpleDateFormat mDateFormat;
//
//        @SuppressLint("SimpleDateFormat")
//        SettingAdapter() {
//            mDateFormat = new SimpleDateFormat(DATE_FORMAT);
//        }
//
//        @Override
//        public int getCount() {
//            return dspSettingsList == null ? 0 : dspSettingsList.size();
//        }
//
//        @Override
//        public UserProfile getItem(int position) {
//            return dspSettingsList == null || dspSettingsList.size() == 0 ? null : dspSettingsList.get(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return dspSettingsList == null || dspSettingsList.size() == 0 ? -1 : dspSettingsList.get(position).getId();
//        }
//
//        @SuppressLint("CheckResult")
//        @Override
//        public View getView(int position, View convertView, ViewGroup parent) {
//            ViewHolder holder;
//            if (convertView == null) {
//                convertView = View.inflate(getActivity(),
//                        R.layout.save_drawer_item, null);
//                holder = new ViewHolder(convertView);
//            } else {
//                holder = (ViewHolder) convertView.getTag();
//            }
//            UserProfile item = getItem(position);
//            holder.tv_name.setText(item.getName());
//            holder.tv_time.setText(mDateFormat.format(item.getCreateDate()));
//            holder.tv_name.setTag(holder);
//            if (item.getMode() == 1) {
//                holder.iv_image.setVisibility(View.VISIBLE);
//            } else {
//                holder.iv_image.setVisibility(View.INVISIBLE);
//            }
//            holder.id = item.getId();
//            holder.btn_send.setOnClickListener(v -> {
//                if (getActivity() != null) {
//                    ((CaDspActivity) getActivity()).showLoadingDialog("Loading", false);
//                }
//                Observable.create((ObservableOnSubscribe<File>) emitter -> {
//                    File file = new File(BtDspApplication.getInstance().getExternalCacheDir() + "/" + "CA DSP " + item.getName() + ".dsp");
//                    if (file.exists()) {
//                        file.delete();
//                    }
//                    try {
//                        file.createNewFile();
//                    } catch (IOException e) {
//                        emitter.onError(e);
//                        return;
//                    }
//                    if (!DataUtil.saveDspToShareFile(file, item)) {
//                        emitter.onError(new IOException("save error"));
//                        return;
//                    }
//                    emitter.onNext(file);
//                }).subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(file -> {
//                            if (getActivity() != null) {
//                                ((CaDspActivity) getActivity()).dismissLoading();
//                            }
//                            Uri fileUri = FileProvider.getUriForFile(
//                                    BtDspApplication.getInstance(),
//                                    BtDspApplication.getInstance().getPackageName() + ".fileprovider",
//                                    file);
//                            Intent intent = new Intent(Intent.ACTION_SEND);
//                            intent.setData(Uri.parse("mailto:"));
//                            intent.putExtra(Intent.EXTRA_EMAIL, "");
//                            intent.setType("text/plain");
//                            intent.putExtra(Intent.EXTRA_STREAM, fileUri);
//                            startActivity(Intent.createChooser(intent, "CA DSP"));
//                        }, e -> {
//                            if (getActivity() != null) {
//                                ((CaDspActivity) getActivity()).dismissLoading();
//                            }
//                            e.printStackTrace();
//                            Toast.makeText(getActivity(), "Share file error!", Toast.LENGTH_SHORT).show();
//                        });
//            });
//            return convertView;
//        }
//
//        class ViewHolder {
//
//            int id;
//            TextView tv_name;
//            TextView tv_time;
//            ImageView iv_image;
//            ImageButton btn_send;
//
//            public ViewHolder(View view) {
//                tv_name = view.findViewById(android.R.id.text1);
//                tv_time = view.findViewById(android.R.id.text2);
//                iv_image = view.findViewById(R.id.img);
//                btn_send = view.findViewById(R.id.btn_send_email);
//                view.setTag(this);
//            }
//        }
//
//    }
//
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//    }
//}
